import urllib.request as ur
import urllib.parse as up
import json
import os
import time

while True:
    content = input('请输入需要翻译的内容（输入“quit”退出程序）：')
    

    if content == 'quit':
        break
    elif content == '':
        print('空，请重新输入：')
    else:
        url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

        '''
        head = {}
        head['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
        req = ur.Request(url, data, head)
        '''

        data = {}
        data['type'] = 'AUTO'
        data['i'] = content
        data['doctype'] = 'json'
        data['smartresult'] = 'dict'
        data['client'] = 'fanyideskweb'
        data['salt'] = '1531896840732'
        data['version'] = '2.1'
        data['keyfrom'] = 'fanyi.web'
        data['action'] = 'FY_BY_REALTIME'
        data['typoResult'] = 'false'

        data = up.urlencode(data).encode('utf-8')
        req = ur.Request(url, data)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36')
        response = ur.urlopen(url, data)
        html = response.read().decode('utf-8')
        target = json.loads(html)
        target1 = target['translateResult'][0][0]['tgt']
        print('翻译结果（中文）: %s' % (target1))
        print('稍等3秒' )
        time.sleep(3)
